package com.tiyende.kash.loop.ui.activity

import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.view.Gravity
import android.view.View
import androidx.core.graphics.toColorInt
import com.tiyende.kash.loop.R
import com.tiyende.kash.loop.TiyendeApp
import com.tiyende.kash.loop.common.CommonActivity
import com.tiyende.kash.loop.databinding.TiyendeActivityApplyLoanBinding
import com.tiyende.kash.loop.databinding.TiyendeActivityApplyLoanDetailsItemBinding
import com.tiyende.kash.loop.event.TiyendeEventData
import com.tiyende.kash.loop.event.TiyendeEventPointType
import com.tiyende.kash.loop.ui.contract.IViewContract
import com.tiyende.kash.loop.ui.dialog.TiyendeLoanApplyGuideDialog
import com.tiyende.kash.loop.ui.presenter.TiyendeLoanApplyPresenter
import com.tiyende.kash.loop.utils.helper.TiyendeOrderHelper
import com.tiyende.kash.loop.utils.helper.TiyendeProcessHelper
import com.tiyende.kash.loop.utils.shared.TiyendeSharedHelper
import com.tiyende.kash.loop.utils.shared.TiyendeSharedKey
import com.tiyende.kash.loop.utils.track.TrackPointManager
import com.tiyende.kash.loop.weight.pickerview.adapter.ArrayWheelAdapter
import com.tiyende.kash.loop.weight.wheelview.view.WheelView
import org.json.JSONArray
import org.json.JSONObject
import java.math.BigDecimal


/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/9/25 19:21
 * @Annotation：申请贷款
 */
class TiyendeLoanApplyActivity: CommonActivity(),IViewContract.ITiyendeLoanApplyView {
    lateinit var binding: TiyendeActivityApplyLoanBinding
    private var presenter: TiyendeLoanApplyPresenter? = null
    private var amountList: ArrayList<String>? = null
    private var applyLoanAmount = 0

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, TiyendeLoanApplyActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun getTiyendeRootView(): View {
        binding = TiyendeActivityApplyLoanBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initTiyendeView() {
        setTiyendeTitleBarVisibility(View.VISIBLE)
        setTiyendeTextTitleVisibility(View.GONE)
        setTiyendeBackBtnRes(R.mipmap.tiyende_back_white)
        setTiyendeRightBtnRes(R.mipmap.tiyende_customer_white)
        setTiyendeSwitchLangBtnRes(R.mipmap.tiyende_language_icon)
        eventRemark = "LoanApply_Page"

        initTiyendeApplyLoanRefreshLayout()
        initTiyendeAmountWheelView()
        binding.applyContentLayout.visibility = View.GONE
        binding.btnApplySubmit.isEnabled = false
//        binding.textApplyAmount.text = getApplyAvailableAmount()
    }

    override fun initTiyendeListener() {
        super.initTiyendeListener()
        binding.wheelView.setOnItemSelectedListener { index ->
            amountList?.let {
                if (it.size >= index){
                    applyLoanAmount = it[index].toInt()
                }
            }
            showTiyendeLoading()
            presenter?.requestApplyDataAction(false)
        }

        //提交
        binding.btnApplySubmit.setOnClickListener {
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_LOAN_APPLY_SUBMIT,getTiyendeLoanApplyAmount())
            // TODO: 申贷页提交按钮 需上报所有埋点
            TrackPointManager.getInstance().manualReport()

            showTiyendeLoading()
            presenter?.createApplyOrderAction()
        }
        //返回
        binding.btApplyLoanReturn.setOnClickListener {
            finish()
        }
    }

    override fun loadTiyendeData() {
        if (presenter == null){
            presenter = TiyendeLoanApplyPresenter(this)
        }
        showTiyendeLoading()
        presenter?.requestApplyDataAction()
    }

    /* 初始化刷新 */
    private fun initTiyendeApplyLoanRefreshLayout() {
        binding.applyRefreshLayout.setColorSchemeResources(R.color.theme,R.color.purple_500)
        binding.applyRefreshLayout.setOnRefreshListener {
            presenter?.requestApplyDataAction()
        }
    }

    /* 初始化额度选择WheelView */
    private fun initTiyendeAmountWheelView(){
        if (amountList == null){
            amountList = arrayListOf()
        }

        val centerColors = intArrayOf("#ff2e9b95".toColorInt(), "#ff2c366b".toColorInt())
        val outColors = intArrayOf("#ffb0e1e2".toColorInt(), "#ff329f97".toColorInt())
        binding.wheelView.setTextShaderCenter(centerColors)
        binding.wheelView.setTextShaderOut(centerColors)
        binding.wheelView.setLineSpacingMultiplier(1.4f)
        binding.wheelView.setItemsVisibleCount(3)
        binding.wheelView.setAlphaGradient(true)
        binding.wheelView.setLabel("")
        binding.wheelView.setGravity(Gravity.CENTER)
        binding.wheelView.setTypefaceCenter(TiyendeApp.app.getBlackTypeface())
        binding.wheelView.setTypefaceOut(TiyendeApp.app.getMediumTypeface())
        binding.wheelView.setTypefaceLable(Typeface.createFromAsset(assets,"fonts/Roboto-Regular.ttf"))
        binding.wheelView.setDividerColor("#00000000".toColorInt())
        binding.wheelView.setDividerType(WheelView.DividerType.WRAP)
        binding.wheelView.adapter = ArrayWheelAdapter(amountList)
        binding.wheelView.setCyclic(true)
    }

    /**
     * 获取贷款金额
     */
    override fun getTiyendeLoanApplyAmount(): String {
        return applyLoanAmount.toString()
    }

    /**
     * 获取贷款期限
     */
    override fun getTiyendeLoanApplyDays(): String {
        return ""
    }

    /**
     * 不可选择贷款额度
     */
    override fun showTiyendeLoanApplyNotOptionalViews(data: JSONObject) {
        binding.wheelView.setCyclic(false)
        //最大值为剩余额度
        val maxAmount = BigDecimal(data.optString("availableAmount")).stripTrailingZeros().toPlainString().toInt()
        //颗粒度
        val granularity = data.optInt("granularity")
        queryTiyendeApplyLoanAmountList(maxAmount, maxAmount,granularity)
    }

    /**
     * 允许选择贷款额度
     */
    override fun showTiyendeLoanApplyOptionalViews(data: JSONObject, showAnim: Boolean) {
        binding.wheelView.setCyclic(true)
        //最小可选额度
        var minAmount = BigDecimal(data.optString("minAmount")).stripTrailingZeros().toPlainString().toInt()
        //最大值为剩余额度
        val maxAmount = BigDecimal(data.optString("availableAmount")).stripTrailingZeros().toPlainString().toInt()
        //显示额度
        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString().toInt()
        //颗粒度
        val granularity = data.optInt("granularity")

        //可选最小额度 > 剩余可用额度 ： 最小额度 = 剩余可用额度
        if (minAmount > maxAmount){
            minAmount = maxAmount
        }
        queryTiyendeApplyLoanAmountList(minAmount, maxAmount,granularity)
        var showIndex = 0
        amountList?.let {
            for (i in 0..<it.size){
                if (amount == it[i].toInt()){
                    showIndex = i
                    break
                }
            }
        }
        binding.wheelView.setCurrentItem(showIndex)
        data.put("defaultIndex",showIndex)
        //显示引导dialog
//        showApplyGuideDialog(data)
    }

    /**
     * 设置贷款明细
     */
    override fun showTiyendeLoanApplyDetailsList(data: JSONObject) {
        binding.applyContentLayout.visibility = View.VISIBLE
        binding.btnApplySubmit.isEnabled = true

        //去掉末尾的0
        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        applyLoanAmount = amount.toInt()
        binding.textApplyDays.text = String.format(getString(R.string.tiyende_loan_apply_repayment_days),data.optString("days"))
        //设置单位
        binding.wheelView.setLabel(data.optString("currency"))

        //明细
        val array = data.optJSONArray("detailItemList")
        val detailItemList = arrayListOf<JSONObject>()
        if (array != null){
            for (i in 0..<array.length()){
                val item = array.optJSONObject(i)
                if (item.has("title") && item.optString("title") == "YES"){
                    detailItemList.add(item)
                }
            }
            for (i in 0..<detailItemList.size){
                val obj = detailItemList[i]
                val childArray = JSONArray()
                var isAddChild = false
                for (n in 0..<array.length()){
                    val item = array.optJSONObject(n)
                    if (obj.optString("showName") == item.optString("showName")){
                        isAddChild = true
                        continue
                    }
                    if (item.has("title") && item.optString("title") == "YES"){
                        isAddChild = false
                        continue
                    }
                    if (isAddChild){
                        childArray.put(item)
                    }
                }
                obj.put("childList",childArray)
            }
        }
        if (detailItemList.size >= 1){
            val withdrawItem = detailItemList[0]
            binding.textApplyItemTitle.text = withdrawItem.optString("showName")
            binding.textApplyItemValue.text = withdrawItem.optString("showDetail")
            val childList = withdrawItem.optJSONArray("childList")
            if (childList != null){
                binding.loanApplyWithdrawDetailsLayout.removeAllViews()
                for (i in 0..<childList.length()){
                    val childItem = childList.optJSONObject(i)
                    val itemView = TiyendeActivityApplyLoanDetailsItemBinding.inflate(layoutInflater)
                    itemView.txtDetailsTitle.text = childItem.optString("showName")
                    itemView.txtDetailsValue.text = childItem.optString("showDetail")
                    binding.loanApplyWithdrawDetailsLayout.addView(itemView.root)
                }
            }
        }

        if (detailItemList.size >= 2){
            val repaymentItem = detailItemList[1]
            binding.textRepaymentItemTitle.text = repaymentItem.optString("showName")
            binding.textRepaymentItemValue.text = repaymentItem.optString("showDetail")
            val childList = repaymentItem.optJSONArray("childList")
            if (childList != null){
                binding.loanApplyRepaymentDetailsLayout.removeAllViews()
                for (i in 0..<childList.length()){
                    val childItem = childList.optJSONObject(i)
                    val childView = TiyendeActivityApplyLoanDetailsItemBinding.inflate(layoutInflater)
                    childView.txtDetailsTitle.text = childItem.optString("showName")
                    childView.txtDetailsValue.text = childItem.optString("showDetail")
                    binding.loanApplyRepaymentDetailsLayout.addView(childView.root)
                }
            }
        }
    }

    /**
     * 贷款申请成功
     */
    override fun showTiyendeLoanApplySuccess() {
        //刷新订单列表
        publishEventData(TiyendeEventData(TiyendeEventData.TYPE.TIYENDE_ORDER_REFRESH))
        publishEventData(TiyendeEventData(TiyendeEventData.TYPE.TIYENDE_PROCESS_REFRESH))
    }

    /**
     * 申请失败 订单状态 或 申请状态 验证不通过，需要返回首页显示对应页面
     */
    override fun showTiyendeLoanApplyFailed() {
        hiddenTiyendeLoading()
        finish()
    }

    /**
     * 获取可选申贷金额列表
     */
    private fun queryTiyendeApplyLoanAmountList(minValue: Int,maxValue: Int,granularity: Int){
        if (amountList == null){
            amountList = arrayListOf()
        }
        amountList?.clear()
        var currentValue = minValue
        while (currentValue <= maxValue) {
            amountList?.add(currentValue.toString())
            currentValue += granularity
        }
        if ((maxValue - minValue) % granularity != 0){
            amountList?.add(maxValue.toString())
        }
    }

    override fun hiddenTiyendeLoading() {
        super.hiddenTiyendeLoading()
        binding.applyRefreshLayout.isRefreshing = false
    }

    override fun onTiyendePublishEvent(event: TiyendeEventData) {
        super.onTiyendePublishEvent(event)
        when(event.eventType){
            TiyendeEventData.TYPE.TIYENDE_PROCESS_REFRESHED -> {
                //需要校验 whatsappFlag=”YES“ || smsFlag=”YES“ || telegramFlag=”YES“ || telegramBotFlag=”YES“
                if (TiyendeProcessHelper.isTiyendeAuthenticationCheckMobile()){
                    TiyendeCheckMobileActivity.start(this)
                } else {
                    //不需要校验手机号，进入订单详情
                    TiyendeOrderInfoActivity.start(this,TiyendeOrderHelper.queryOrderId)
                }
                finish()
            }
            TiyendeEventData.TYPE.TIYENDE_REQUEST_ERROR -> {
                hiddenTiyendeLoading()
            }
            else -> {

            }
        }
    }

    /**
     * 展示引导dialog
     */
    private fun showApplyGuideDialog(data: JSONObject){
        val isShowGuide = TiyendeSharedHelper.queryTiyendeSharedBoolean(TiyendeSharedKey.TIYENDE_DIALOG_GUIDE_APPLY_SHOW)
        if (isShowGuide){//已显示过
            return
        }
        //此处展示引导dialog
        TiyendeSharedHelper.addTiyendeSharedData(TiyendeSharedKey.TIYENDE_DIALOG_GUIDE_APPLY_SHOW,true)
        val loanApplyGuideDialog = TiyendeLoanApplyGuideDialog(this)
        loanApplyGuideDialog.setCancelable(true)
        loanApplyGuideDialog.setCanceledOnTouchOutside(true)
        loanApplyGuideDialog.show()
        loanApplyGuideDialog.showTiyendeLoanApplyGuideDatas(data,amountList)

    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_LOAN_APPLY_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_LOAN_APPLY_END)
    }
}